package com.xz.purchase.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.annotation.DataScope;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.core.domain.entity.SysUser;
import com.xz.common.exception.ServiceException;
import com.xz.common.utils.RedisCode;
import com.xz.common.utils.SecurityUtils;
import com.xz.common.utils.StringUtils;
import com.xz.purchase.domain.PurchaseProduct;
import com.xz.purchase.domain.ReturnInfo;
import com.xz.purchase.domain.ReturnProduct;
import com.xz.purchase.mapper.PurchaseProductMapper;
import com.xz.purchase.mapper.ReturnInfoMapper;
import com.xz.purchase.mapper.ReturnProductMapper;
import com.xz.purchase.param.ReturnInfoParam;
import com.xz.purchase.service.IReturnInfoService;
import com.xz.purchase.vo.ReturnInfoNoFlowVo;
import com.xz.purchase.vo.ReturnInfoRepeatFlowVo;
import com.xz.purchase.vo.ReturnInfoVo;
import com.xz.purchase.vo.ReturnProductVo;
import com.xz.repertory.domain.RepertoryFlow;
import com.xz.repertory.service.IRepertoryFlowService;
import com.xz.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采购退货Service业务层处理
 *
 * @author xz
 * @date 2024-1-10 10:38:46
 */
@Service
public class ReturnInfoServiceImpl extends ServiceImpl<ReturnInfoMapper, ReturnInfo> implements IReturnInfoService {


    @Resource
    private PurchaseProductMapper purchaseProductMapper;

    @Resource
    private ReturnProductMapper returnProductMapper;

    @Autowired
    private IRepertoryFlowService iRepertoryFlowService;

    @Autowired
    private ISysUserService sysUserService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult addReturnInfo(ReturnInfoParam param) {
        List<ReturnProduct> productList = param.getProductList();
        if(CollectionUtils.isEmpty(productList)){
            return AjaxResult.error("商品不能为空");
        }
        //仓库所属部门
        ReturnInfo returnInfo = new ReturnInfo();
        returnInfo.setStatus(param.getStatus());
        returnInfo.setSupplierId(param.getSupplierId());
        returnInfo.setSupplierName(param.getSupplierName());
        returnInfo.setRemark(param.getRemark());
        returnInfo.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        returnInfo.setCreateBy(SecurityUtils.getLoginUser().getUserId());
        returnInfo.setReturnNo(RedisCode.getCode("TH"));
        int insert = baseMapper.insert(returnInfo);
        if(insert>0){
            returnInfo = baseMapper.selectById(returnInfo.getId());
            int i = processProductData(productList, returnInfo);
            if(i>0){
                if(returnInfo.getStatus().equals(2)){
                    // 直接确认退货
                    updateStorageAddFlow(returnInfo);
                }
                return AjaxResult.success("新增成功");
            }
        }
        return AjaxResult.error("新增失败");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateReturnInfo(ReturnInfoParam param) {
        if(param.getId()==null){
            return AjaxResult.error("参数id不能为空");
        }
        ReturnInfo returnInfo = baseMapper.selectById(param.getId());
        Date now = new Date();
        param.setUpdateTime(now);
        param.setUpdateBy(SecurityUtils.getUserId());
        returnInfo.setStatus(param.getStatus());
        returnInfo.setSupplierId(param.getSupplierId());
        returnInfo.setSupplierName(param.getSupplierName());
        returnInfo.setRemark(param.getRemark());
        baseMapper.updateById(returnInfo);
        List<ReturnProduct> productList = param.getProductList();
        if(CollectionUtils.isEmpty(productList)){
            return AjaxResult.error("商品不能为空");
        }
        //删除库存商品重新录入
        returnProductMapper.deleteByReturnId(returnInfo.getId());
        int i = processProductData(productList, returnInfo);
        if(i>0){
            if(returnInfo.getStatus().equals(2)){
                // 直接确认退货
                updateStorageAddFlow(returnInfo);
            }
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改失败");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult editStatus(ReturnInfo returnInfo){
        if(Objects.isNull(returnInfo.getId())){
            return AjaxResult.error("参数id不能为空");
        }
        if(!returnInfo.getStatus().equals(4)){
            return AjaxResult.error("状态参数错误");
        }
        ReturnInfo obj = baseMapper.selectById(returnInfo.getId());
        obj.setStatus(returnInfo.getStatus());
        baseMapper.updateById(obj);
        //库存流水
        if(returnInfo.getStatus().equals(2)){
            updateStorageAddFlow(returnInfo);
        }
        return AjaxResult.success("操作成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult importNoFlowExcel(List<ReturnInfoNoFlowVo> list){
        for (ReturnInfoNoFlowVo vo:list) {
            ReturnInfo returnInfo = baseMapper.selectById(vo.getId());
            updateStorageAddNoFlow(returnInfo);
        }
        return AjaxResult.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult importRepeatFlowExcel(List<ReturnInfoRepeatFlowVo> list){
        for (ReturnInfoRepeatFlowVo vo:list) {
            PurchaseProduct purchaseProduct = purchaseProductMapper.selectPurchaseProductById(vo.getPurchaseProductId());
            if(Objects.nonNull(purchaseProduct)){
                Integer availableStock = purchaseProduct.getAvailableStock();
                Integer num = vo.getQuantity();
                availableStock = availableStock+num;
                purchaseProduct.setAvailableStock(availableStock);
                purchaseProductMapper.updateById(purchaseProduct);
            }
        }
        return AjaxResult.success();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult importKcExcel(List<ReturnInfoNoFlowVo> list){
        for (ReturnInfoNoFlowVo vo:list) {
            PurchaseProduct purchaseProduct = purchaseProductMapper.queryByParam(vo);
            if(Objects.nonNull(purchaseProduct)){
                Integer availableStock = purchaseProduct.getAvailableStock();
                Integer num = vo.getNum();
                availableStock = availableStock+num;
                purchaseProduct.setAvailableStock(availableStock);
                purchaseProductMapper.updateById(purchaseProduct);
            }
        }
        return AjaxResult.success();
    }

    //
    private void updateStorageAddNoFlow(ReturnInfo returnInfo){
        // 因为这边是确认收货 所以先更新采购库存
        try {
//            List<PurchaseProduct> returnProductVoList = returnProductMapper.productListByReturnId(returnInfo.getId());
            List<ReturnProduct> returnProductList = returnProductMapper.getListByReturnId(returnInfo.getId());
            Integer type = 2;
            Integer storageType = 3;
            boolean flag = true;
            if(returnInfo.getStatus().equals(3)){
                flag = false;
                type = 2;
                storageType = 4;
            }
            List<PurchaseProduct> flowDataList = new ArrayList<>();
            if(flag){
                for (ReturnProduct returnProduct:returnProductList) {
                    PurchaseProduct queryProductParam = new PurchaseProduct();
                    BeanUtils.copyProperties(returnProduct,queryProductParam);
                    queryProductParam.setSupplierId(returnInfo.getSupplierId());
                    List<PurchaseProduct> purchaseProductList = purchaseProductMapper.getListByParam(queryProductParam);
                    List<PurchaseProduct> purchaseProducts = iRepertoryFlowService.convertFlowData(purchaseProductList, returnProduct.getReturnNum(), returnInfo.getReturnNo(),returnInfo.getId());
                    for (PurchaseProduct purchaseProduct:purchaseProducts) {
                        purchaseProduct.setCreateTime(returnInfo.getCreateTime());
                        purchaseProduct.setRemark(returnInfo.getRemark());
                        purchaseProduct.setDeptId(returnInfo.getDeptId());
                    }
                    flowDataList.addAll(purchaseProducts);
                }
            }else{
                // 冲红
                RepertoryFlow repertoryFlowParam = new RepertoryFlow();
                // 查采购退货的
                repertoryFlowParam.setStorageType(3);
                repertoryFlowParam.setBusinessId(returnInfo.getId());
                List<PurchaseProduct> repertoryFlows = iRepertoryFlowService.selectListByRepertoryFlow(repertoryFlowParam);
                for (PurchaseProduct purchaseProduct:repertoryFlows) {
                    Integer inventoryQuantity = purchaseProduct.getInventoryQuantity();
                    Integer availableStock = purchaseProduct.getAvailableStock();
                    purchaseProduct.setAvailableStock(availableStock+inventoryQuantity);
                    purchaseProductMapper.updateById(purchaseProduct);
                }
                flowDataList.addAll(repertoryFlows);
            }
            boolean repertoryFlow = iRepertoryFlowService.saveRepertoryFlow(flowDataList, type, storageType);
            if(!repertoryFlow){
                throw new ServiceException("退货失败！原因：增加退货库存流水失败。");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void updateStorageAddFlow(ReturnInfo returnInfo){
        // 因为这边是确认收货 所以先更新采购库存
        try {
//            List<PurchaseProduct> returnProductVoList = returnProductMapper.productListByReturnId(returnInfo.getId());
            List<ReturnProduct> returnProductList = returnProductMapper.getListByReturnId(returnInfo.getId());
            Integer type = 2;
            Integer storageType = 3;
            boolean flag = true;
            if(returnInfo.getStatus().equals(3)){
                flag = false;
                type = 2;
                storageType = 4;
            }
            List<PurchaseProduct> flowDataList = new ArrayList<>();
            if(flag){
                for (ReturnProduct returnProduct:returnProductList) {
                    PurchaseProduct queryProductParam = new PurchaseProduct();
                    BeanUtils.copyProperties(returnProduct,queryProductParam);
                    queryProductParam.setSupplierId(returnInfo.getSupplierId());
                    List<PurchaseProduct> purchaseProductList = purchaseProductMapper.getListByParam(queryProductParam);
                    List<PurchaseProduct> purchaseProducts = iRepertoryFlowService.convertFlowData(purchaseProductList, returnProduct.getReturnNum(), returnInfo.getReturnNo(),returnInfo.getId());
                    purchaseProducts.stream().forEach(s->{
                        s.setCreateTime(returnInfo.getCreateTime());
                        s.setRemark(returnProduct.getRemark());
                        s.setCreateBy(returnInfo.getCreateBy());
                    });
                    flowDataList.addAll(purchaseProducts);
                }
            }else {
                // 冲红
                RepertoryFlow repertoryFlowParam = new RepertoryFlow();
                // 查采购退货的
                repertoryFlowParam.setStorageType(3);
                repertoryFlowParam.setBusinessId(returnInfo.getId());
                List<PurchaseProduct> repertoryFlows = iRepertoryFlowService.selectListByRepertoryFlow(repertoryFlowParam);
                for (PurchaseProduct purchaseProduct:repertoryFlows) {
                    Integer inventoryQuantity = purchaseProduct.getInventoryQuantity();
                    Integer availableStock = purchaseProduct.getAvailableStock();
                    purchaseProduct.setAvailableStock(availableStock+inventoryQuantity);
                    purchaseProductMapper.updateById(purchaseProduct);
                }
                repertoryFlows.stream().forEach(s->{
                    s.setCreateTime(returnInfo.getCreateTime());
                    s.setCreateBy(returnInfo.getCreateBy());
                });
                flowDataList.addAll(repertoryFlows);

            }
            boolean repertoryFlow = iRepertoryFlowService.saveRepertoryFlow(flowDataList, type, storageType);
            if(!repertoryFlow){
                throw new ServiceException("退货失败！原因：增加退货库存流水失败。");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private int processProductData(List<ReturnProduct> productList,ReturnInfo returnInfo){
        List<Long> warehouseIds = new ArrayList<>();
        List<String> warehouseNames = new ArrayList<>();
        productList.stream().forEach(i-> {
            i.setReturnId(returnInfo.getId());
            returnProductMapper.insert(i);
            warehouseIds.add(i.getWarehouseId());
            warehouseNames.add(i.getWarehouseName());
        });
        int sumNumber = productList.stream().map(e -> e.getReturnNum()).reduce(Integer::sum).get();//求和
        returnInfo.setReturnNum(sumNumber);
        returnInfo.setWarehouseIds(StringUtils.join(warehouseIds,","));
        returnInfo.setWarehouseNames(StringUtils.join(warehouseNames,","));
        int i = baseMapper.updateById(returnInfo);
        return i;
    }

    @DataScope(deptAlias = "d", userAlias = "u")
    @Override
    public List<ReturnInfo> queryList(ReturnInfo returnInfo){
        List<ReturnInfo> returnInfos = baseMapper.queryList(returnInfo);
        if(!CollectionUtils.isEmpty(returnInfos)){
            returnInfos.forEach(data->{
                if(StringUtils.isNotEmpty(data.getWarehouseNames()) && data.getWarehouseNames().contains(",")){
                    String[] array = data.getWarehouseNames().split(",");
                    String warehouseNames = Arrays.stream(array).distinct().collect(Collectors.joining(","));
                    data.setWarehouseNames(warehouseNames);
                }
            });
        }
        return returnInfos;
    }

    @Override
    public ReturnInfoVo returnDetailById(Long id){
        ReturnInfo returnInfo = baseMapper.selectById(id);
        ReturnInfoVo returnInfoVo = new ReturnInfoVo();
        BeanUtils.copyProperties(returnInfo,returnInfoVo);
        SysUser sysUser = sysUserService.selectUserById(returnInfo.getCreateBy());
        returnInfoVo.setUserName(sysUser.getUserName());
        List<ReturnProductVo> returnProductVoList = returnProductMapper.findListByReturnId(id);
        returnInfoVo.setReturnProductVoList(returnProductVoList);
        return returnInfoVo;
    }

    @Override
    public AjaxResult redInkEntry(ReturnInfo returnInfo){
        if(Objects.isNull(returnInfo.getId())){
            return AjaxResult.error("参数不能为空！");
        }
        ReturnInfo returnInfoData = baseMapper.selectById(returnInfo.getId());
        if(new Integer(3).equals(returnInfoData.getStatus())){
            return AjaxResult.error("该采购退货单已冲红，请勿重复操作！");
        }
        returnInfoData.setStatus(3);
        baseMapper.updateById(returnInfoData);
        // 库存流水
        updateStorageAddFlow(returnInfoData);
        return AjaxResult.success("冲红成功");
    }


//    /**
//     * 冲红
//     * @param blushVo
//     * @return
//     */
//    @Override
//    public AjaxResult blush(BlushVo blushVo) {
//        if(blushVo.getType()==1){
//            if(CollectionUtils.isEmpty(blushVo.getIdList())){
//                return AjaxResult.error("请选择冲红商品");
//            }
//        }
//        if(blushVo.getType()==2){
//            List<PurchaseProduct> list = iPurchaseProductService.list(new QueryWrapper<PurchaseProduct>().eq("purchase_id", blushVo.getId()).eq("status", 1));
//            if(!CollectionUtils.isEmpty(list)){
//                List<Long> collected = list.stream().map(i -> i.getId()).collect(Collectors.toList());
//                blushVo.setIdList(collected);
//            }
//        }
//        if(CollectionUtils.isEmpty(blushVo.getIdList())){
//            return AjaxResult.success("暂无可冲红商品");
//        }
//        int blush = iPurchaseProductService.blush(blushVo.getIdList());
//        if(blush>0){
//            int count = iPurchaseProductService.count(new QueryWrapper<PurchaseProduct>().eq("purchase_id", blushVo.getId()).eq("status", 1));
//            Purchase purchase = baseMapper.selectById(blushVo.getId());
//            if(Objects.isNull(purchase)){
//                return AjaxResult.error("冲红失败");
//            }
//            purchase.setStatus(count>0?4:3);
//            purchase.setUpdateTime(DateUtils.getNowDate());
//            purchase.setUpdateBy(SecurityUtils.getUserId());
//            int updatePurchase = purchaseMapper.updatePurchase(purchase);
//            if(updatePurchase>0){
//                blushVo.getIdList().stream().forEach(i->{
//                    PurchaseProduct purchaseProductInfo = iPurchaseProductService.getPurchaseProductInfo(i);
//                    purchaseProductInfo.setCreateBy(SecurityUtils.getUserId());
//                    if(!Objects.isNull(purchaseProductInfo)){
//                        Object object = JSON.parseObject(JSON.toJSONString(purchaseProductInfo), Object.class);
//                        iRepertoryFlowService.saveRepertoryFlow(iRepertoryFlowService.dataRepertoryFlow(object, 1,2));
//                    }
//                });
//            }
//            return AjaxResult.success("冲红成功");
//        }
//        return AjaxResult.error("冲红失败");
//    }
}
